/*******************************************************************
 * 外语翻译平台(translate) 
 *
 * 成都一亿信息技术公司 版权所有
 * 
 * Copyright (C) 2010 Transer Information Technology Co., Ltd.
 *
 * @Version : 1.0  2011-1-3 下午09:37:02
 *
 * CookieUtils.java 
 *
 *******************************************************************/
package com.transer.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * class defination are there
 * 
 * @author Mark
 * 
 * @version 1.0 ywengineer@gmail.com
 * 
 */
public class CookieUtils {
	private CookieUtils() {
	}

	/**
	 * 添加COOKIE
	 * 
	 * @param key
	 * @param value
	 * @param uri
	 * @param maxAge
	 * @param response
	 */
	public static void addCookie(String key, String value, String uri, int maxAge, HttpServletResponse response) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(uri);
		response.addCookie(cookie);
	}

	/**
	 * 获取COOKIE值
	 * 
	 * @param key
	 * @param request
	 * @return
	 */
	public static String getValue(String key, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * 删除所有COOKIE
	 * 
	 * @param request
	 * @param response
	 */
	public static void removeAllCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				removeCookie(cookie, cookie.getPath(), response);
			}
		}
	}

	/**
	 * 删除COOKIE
	 * 
	 * @param cookie
	 * @param uri
	 * @param response
	 */
	public static void removeCookie(Cookie cookie, String uri, HttpServletResponse response) {
		cookie.setMaxAge(0);
		cookie.setPath(uri);
		response.addCookie(cookie);
	}
}
